// pages/apply/apply.js
const { post } = require("../../utils/request.js");
const { handleGlobalError } = require("../../utils/globalErrorHandler.js");

Page({
  data: {
    formData: {
      realName: "",
      phone: "",
      address: "",
      applyReason: "",
    },
    agreed: false,
    canSubmit: false,
    submitText: "提交申请",
    submitting: false,
    // 字段验证状态
    fieldErrors: {
      realName: "",
      phone: "",
      address: "",
      applyReason: "",
    },
  },

  onLoad() {
    this.checkFormValid();
  },

  // 输入框变化
  onInputChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = String(e.detail.value || ""); // 确保是字符串类型

    this.setData({
      [`formData.${field}`]: value,
    });

    // 实时校验
    this.validateField(field, value);
    this.checkFormValid();
  },

  // 协议勾选切换
  toggleAgreement(e) {
    const newAgreed = !this.data.agreed;
    this.setData({
      agreed: newAgreed,
    });
    this.checkFormValid();
  },

  // 协议勾选
  onAgreementChange(e) {
    this.setData({
      agreed: e.detail.value,
    });
    this.checkFormValid();
  },

  // 单个字段校验
  validateField(field, value) {
    let error = "";

    switch (field) {
      case "realName":
        if (!value.trim()) {
          error = "真实姓名不能为空";
        } else if (value.trim().length < 2) {
          error = "真实姓名至少2个字符";
        } else if (value.trim().length > 20) {
          error = "真实姓名不能超过20个字符";
        } else if (!/^[\u4e00-\u9fa5a-zA-Z\s]+$/.test(value.trim())) {
          error = "真实姓名只能包含中文、英文和空格";
        }
        break;

      case "phone":
        const phoneValue = value.trim();
        if (!phoneValue) {
          error = "联系电话不能为空";
        } else if (!/^1[3-9]\d{9}$/.test(phoneValue)) {
          error = "请输入正确的手机号码";
        }
        break;

      case "address":
        if (!value.trim()) {
          error = "联系地址不能为空";
        } else if (value.trim().length < 5) {
          error = "联系地址至少5个字符";
        } else if (value.trim().length > 200) {
          error = "联系地址不能超过200个字符";
        }
        break;

      case "applyReason":
        if (!value.trim()) {
          error = "申请理由不能为空";
        } else if (value.trim().length < 10) {
          error = "申请理由至少10个字符";
        } else if (value.trim().length > 500) {
          error = "申请理由不能超过500个字符";
        }
        break;
    }

    this.setData({
      [`fieldErrors.${field}`]: error,
    });
  },
  checkFormValid() {
    const { formData, agreed, fieldErrors } = this.data;

    // 检查所有字段是否填写
    const realNameFilled = !!formData.realName.trim();
    const phoneFilled = !!formData.phone.trim();
    const addressFilled = !!formData.address.trim();
    const reasonFilled = !!formData.applyReason.trim();

    const allFieldsFilled =
      realNameFilled && phoneFilled && addressFilled && reasonFilled;

    // 检查是否有字段错误
    const hasErrors = Object.values(fieldErrors).some((error) => error !== "");

    // 必须满足：所有字段填写 + 无错误 + 同意协议
    const isValid = allFieldsFilled && !hasErrors && agreed;

    this.setData({
      canSubmit: isValid && !this.data.submitting,
    });
  },

  // 验证表单数据
  validateForm() {
    const { formData } = this.data;
    const errors = [];

    // 验证真实姓名
    if (!formData.realName.trim()) {
      errors.push("真实姓名不能为空");
    }

    // 验证手机号
    if (!formData.phone.trim()) {
      errors.push("联系电话不能为空");
    } else if (!/^1[3-9]\d{9}$/.test(formData.phone.trim())) {
      errors.push("手机号格式不正确");
    }

    // 验证联系地址
    if (!formData.address.trim()) {
      errors.push("联系地址不能为空");
    }

    // 验证申请理由
    if (!formData.applyReason.trim()) {
      errors.push("申请理由不能为空");
    }

    return errors;
  },

  // 提交申请
  async submitApplication(e) {
    if (!this.data.canSubmit) {
      wx.showToast({
        title: "请完善所有信息",
        icon: "none",
      });
      return;
    }

    // 验证表单
    const errors = this.validateForm();
    if (errors.length > 0) {
      wx.showToast({
        title: errors[0],
        icon: "none",
      });
      return;
    }

    this.setData({
      submitText: "提交中...",
      canSubmit: false,
      submitting: true,
    });

    try {
      // 准备提交数据
      const submitData = {
        realName: this.data.formData.realName.trim(),
        phone: this.data.formData.phone.trim(),
        address: this.data.formData.address.trim(),
        applyReason: this.data.formData.applyReason.trim(),
      };

      // 调用API接口
      const response = await post("/client/customer/apply-leader", submitData);

      console.log("接口返回数据:", response);

      if (response.code === 0) {
        // 申请成功
        wx.showModal({
          title: "申请成功",
          content:
            "您的分销商申请已提交成功，我们将在1-3个工作日内审核，请耐心等待。",
          showCancel: false,
          success: () => {
            wx.navigateBack();
          },
        });
      } else {
        // 申请失败，显示服务器返回的错误信息
        console.log("申请失败，错误信息:", response.message);
        wx.showModal({
          title: "申请失败",
          content: response.message || "申请提交失败，请稍后重试",
          showCancel: false,
        });
      }
    } catch (error) {
      // 使用全局错误处理
      handleGlobalError(error, {
        title: "申请失败",
        showModal: true,
      });
    } finally {
      // 恢复按钮状态
      this.setData({
        submitText: "提交申请",
        submitting: false,
      });
      this.checkFormValid();
    }
  },

  // 查看分销商协议
  viewAgreement() {
    wx.showModal({
      title: "分销商协议",
      content: "分销商协议内容...",
      showCancel: false,
    });
  },

  // 查看隐私政策
  viewPrivacy() {
    wx.showModal({
      title: "隐私政策",
      content: "隐私政策内容...",
      showCancel: false,
    });
  },
});
